package Scuttlebutt;

import java.awt.dnd.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.io.*;
import javax.swing.filechooser.*;
import java.net.URL;
import java.net.MalformedURLException;
import glue.*;

public class EditPane extends JTabbedPane implements ChangeListener,DropTargetListener 
{
	Scuttlebutt parent = null;
	
	
	class TabbedPaneCloseButtonUI extends BasicTabbedPaneUI {
		Scuttlebutt parent = null;
	    public TabbedPaneCloseButtonUI(Scuttlebutt parent) {
	        super();
	        this.parent = parent;
	    }
	 
	    protected void paintTab(
	        Graphics g,
	        int tabPlacement,
	        Rectangle[] rects,
	        int tabIndex,
	        Rectangle iconRect,
	        Rectangle textRect) {
	 
	        super.paintTab(g, tabPlacement, rects, tabIndex, iconRect, textRect);
	 
	        Rectangle rect = rects[tabIndex];
	        if(tabPane.isEnabledAt(tabIndex)){
	        	g.setColor(Color.black);
	        }else{
		        g.setColor(Color.GRAY);
	        }
	        g.drawRect(rect.x + rect.width -19, rect.y + 4, 13, 12);
	        g.drawLine(
	            rect.x + rect.width -16,
	            rect.y + 7,
	            rect.x + rect.width -10,
	            rect.y + 13);
	        g.drawLine(
	            rect.x + rect.width -10,
	            rect.y + 7,
	            rect.x + rect.width -16,
	            rect.y + 13);
	        g.drawLine(
	            rect.x + rect.width -15,
	            rect.y + 7,
	            rect.x + rect.width -9,
	            rect.y + 13);
	        g.drawLine(
	            rect.x + rect.width -9,
	            rect.y + 7,
	            rect.x + rect.width -15,
	            rect.y + 13);
	    }
	 
	    protected int calculateTabWidth(
	        int tabPlacement,
	        int tabIndex,
	        FontMetrics metrics) {
	        return super.calculateTabWidth(tabPlacement, tabIndex, metrics) + 24;
	    }
	    
	 
	    protected MouseListener createMouseListener() {
	        return new MyMouseHandler();
	    }
	 
	    public class MyMouseHandler extends MouseHandler {
	        public MyMouseHandler() {
	            super();
	        }
	        public void mouseReleased(MouseEvent e) {
	            int x = e.getX();
	            int y = e.getY();
	            int tabIndex = -1;
	            int tabCount = tabPane.getTabCount();
	            for (int i = 0; i < tabCount; i++) {
	                if (rects[i].contains(x, y)) {
	                    tabIndex = i;
	                    break;
	                }
	            }
		        if((tabIndex >= 0) &&(!tabPane.isEnabledAt(tabIndex))){
		        	return;
		        }
			    if (tabIndex >= 0 && ! e.isPopupTrigger()) {
		                Rectangle tabRect = rects[tabIndex];
		                y = y - tabRect.y;
		                if ((x >= tabRect.x + tabRect.width - 18)
		                    && (x <= tabRect.x + tabRect.width - 8)
		                    && (y >= 5)
		                    && (y <= 15)) {
							if(parent.getProject() != null){
								Tab t = (Tab)((JScrollPane)tabPane.getComponentAt(tabIndex)).getViewport().getView();
								t.Save();
								parent.getProject().removeOpened(t.getFile());
								parent.SaveProject();
							}
							try{
		                   	 	tabPane.remove(tabIndex);
							}catch(java.lang.IndexOutOfBoundsException ex){
								System.out.println(ex);
							}
		                }
		            }
		        }
	    	}	   
		}

	
	public EditPane(Scuttlebutt parent)
	{
		this.parent = parent;
		setUI(new TabbedPaneCloseButtonUI(parent));
		setDropTarget(new DropTarget(this, this));	
	}
	
	public void New(){
		add( new JScrollPane(new Tab(parent, new String("<HTML>\n<HEAD>\n<\\HEAD>\n<BODY>\n<\\BODY>\n<\\HTML>")), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
		setSelectedComponent(getComponentAt(getTabCount()-1));
	}
	
	public void New(Scuttlebutt parent, String file){
		File f = new File(file);
		add( new JScrollPane(new Tab(parent, file), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS), f.getName());
		setSelectedComponent(getComponentAt(getTabCount()-1));
	}
	
	public void SaveAllTabs(){
//		System.out.println("Editpane saveAllTabs");
		int x = 0;
		while ( x < getTabCount()) {
			Tab t = (Tab)((JScrollPane)getComponentAt(x)).getViewport().getView();
			if(t.getFile() == null){
				setSelectedComponent(getComponentAt(x));
				SaveAs();
			}else{
//				System.out.println("tab:" + t.getFile());
				t.Save();
			}
		 	++x;
		}
	}
	
	public void undoAllNotUploadedForNotSaved(){
		int x = 0;
		while ( x < getTabCount()) {
			Tab t = (Tab)((JScrollPane)getComponentAt(x)).getViewport().getView();
			t.undoNotUploaded();
		 	++x;
		}

	}

	public void Save(){
		Tab t = (Tab)((JScrollPane)getSelectedComponent()).getViewport().getView();
		if(t.getFile() == null){
			SaveAs();
		}else{
			t.Save();
		}
	}
	
	public String getSelectedTabFile(){
		Tab t = (Tab)((JScrollPane)getSelectedComponent()).getViewport().getView();
		return t.getFile();
	}
	
	public void SaveAs(){
		Tab t = (Tab)((JScrollPane)getSelectedComponent()).getViewport().getView();
		JFileChooser chooser = new JFileChooser();
		chooser.addChoosableFileFilter(new SuperFileFilter(new String("htm,html")));
		if(chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION){
			t.setFile(chooser.getSelectedFile().getPath());
			setTitleAt(getSelectedIndex(), chooser.getSelectedFile().getName());
			Save();
		}
	}
	
	public boolean alreadyExists(String file){
		int x = 0;
		boolean found = false;
		while ( (!found) && (x < getTabCount()) ) {

			if(((Tab)((JScrollPane)getComponentAt(x)).getViewport().getView()).getFile()./*getPath().*/compareToIgnoreCase(file) == 0){
				found = true;
				setSelectedComponent(getComponentAt(x));
			}
		 	++x;
		}
		return found;
	}
	
	public void remove(String file){
		int x = 0;
		boolean found = false;
		while ((!found) && (x < getTabCount())){
			Tab t = (Tab)((JScrollPane)getComponentAt(x)).getViewport().getView();
			if( t.getFile().compareToIgnoreCase(file)== 0){
				removeTabAt(x);
				parent.getProject().removeOpened(((Tab)((JScrollPane)getComponentAt(x)).getViewport().getView()).getFile()/*.getPath()*/);
				found = true;
			}
		 	++x;
		}

	}
	
	public Tab search(String file){
		int x = 0;
		Tab found = null;
		while ( (found == null) && (x < getTabCount()) ) {
			Tab t = (Tab)((JScrollPane)getComponentAt(x)).getViewport().getView();
			if( t.getFile().compareToIgnoreCase(file)== 0){
				found = t;
			}
		 	++x;
		}
		return found;
	}
	
	public void setEnabledAt(String txt, boolean enabled){
		int idx = indexOfTab(txt);
		if(idx != -1)
			setEnabledAt(idx, enabled);
	}
	
	public void enableAllTabs(boolean state){
		for(int x = 0; x < getTabCount(); x++){
			Tab t = (Tab)((JScrollPane)getComponentAt(x)).getViewport().getView();
			t.setEditable(state);
//			setEnabledAt(t.getFile(), state);
			setEnabledAt(x, state);
		}
	}
	
	public boolean needsToBeSaved(){
		Tab t = (Tab)((JScrollPane)getSelectedComponent()).getViewport().getView();
		if(t == null)
			return false;
		return t.needsToBeSaved();
	}
	
	
	public void OpenWithoutCheck(String file){
		File f = new File(file);
		if((getExtension(f).compareToIgnoreCase("html") == 0) ||
		(getExtension(f).compareToIgnoreCase("htm") == 0) ||
		(getExtension(f).compareToIgnoreCase("jsp") == 0) ||
		(getExtension(f).compareToIgnoreCase("py") == 0) ||
		(getExtension(f).compareToIgnoreCase("txt") == 0)){
			Tab t = new Tab(parent, file);
			add(f.getName(),new JScrollPane(t, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS ));
			setSelectedComponent(getComponentAt(getTabCount()-1));	
//			t.getCaret().setVisible(true);
			t.setEditable(false);
			setEnabledAt(getTabCount() - 1, false);
		}
		
		if(parent.getProject() != null){
			parent.getProject().addOpened(file);
		}
		
		f = null;
	}
	
	public void Open(String file){
		File f = new File(file);
		if(!alreadyExists(file)){
			if((getExtension(f).compareToIgnoreCase("html") == 0) ||
			(getExtension(f).compareToIgnoreCase("htm") == 0) ||
			(getExtension(f).compareToIgnoreCase("jsp") == 0) ||
			(getExtension(f).compareToIgnoreCase("py") == 0) ||
			(getExtension(f).compareToIgnoreCase("txt") == 0)){
				Tab t = new Tab(parent, file);
				add(f.getName(),new JScrollPane(t, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS ));
				setSelectedComponent(getComponentAt(getTabCount()-1));	
				t.grabFocus();
//				t.setEditable(true);
//				setEnabledAt(getTabCount() - 1, true);
			}
			if(parent.getProject() != null){
				parent.getProject().addOpened(file);
			}
		}else{
			Tab t = search(file);
			if(t == null)
				return;
			t.getCaret().setVisible(true);
		}
			
		
		f = null;
	}

    public String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
    }
	
	public void dragEnter(DropTargetDragEvent d0)
	{
	}

	public void dragExit(DropTargetEvent d0)
	{
	}

	public void dragOver(DropTargetDragEvent d0)
	{
	}

	public void drop(DropTargetDropEvent d0)
	{
	}

	public void dropActionChanged(DropTargetDragEvent d0)
	{
	}

	public void stateChanged(ChangeEvent c0)
	{
/*		System.out.println("Tab statechanged");
		JScrollPane pane = (JScrollPane)getSelectedComponent();
		if(pane == null){
			parent.getBrowsePane().getEdit().setText("");
			return;
		}
			
		Tab t = (Tab)pane.getViewport().getView();
		System.out.println("Tab statechanged");

		if(t == null)
			return;
		try{
			if(t.file != null){
				parent.getBrowsePane().LoadPage(new URL(new String("file:///" + t.file)));
//				parent.getBrowsePane().LoadPage(t.getFile());
				parent.setTitle("Scuttlebutt: " + t.file);
			}else{
				parent.getBrowsePane().getEdit().setText("");
				parent.setTitle("Scuttlebutt");
			}		
		}catch(MalformedURLException me){
			
			System.err.println("EditPane MalformedUrlException");
			System.err.println(me.toString());
		}*/
	}
	

}

